package com.itqian.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author shishuqian
 * date 2022/4/14
 * time 14:03
 **/
@RestController
@RequestMapping("/img")
public class ImgController {

    @Value("${user.file.path}")
    private String filePath;

    @Value("${user.file.visit}")
    private String visit;

    @GetMapping("/test")
    public String test(){
        return "hello eorder-img";
    }

    /**
     *
     * @author shishuqian
     * @desc  保存上传的图片，返回图片访问地址
     */
    @PostMapping("/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile multipartFile){
        //获取文件名
        String filename = multipartFile.getOriginalFilename();
        //获取文件名后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
        //重新生成文件名
        filename = uuid + suffix;

        Map<String, Object> map = new HashMap<>();
        try {
            //将图片保存到文件夹里
            multipartFile.transferTo(new File(filePath + filename));
        } catch (IOException e) {
            e.printStackTrace();
            map.put("code",-1);
            map.put("msg","上传图片失败");
            map.put("data",null);
            return map;
        }
        map.put("code",0);
        map.put("msg","上传成功");
        map.put("data",visit+filename);
        return map;
    }




}
